﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows;
using Microsoft.Win32;
using MyUtils;
using MyUtils.Performance;
using XTrace.Compatibility;

namespace XTrace.Viewer
{

	public class App : Application
	{
// ReSharper disable InconsistentNaming
		static readonly XTraceSource Trace = new XTraceSource("App");
// ReSharper restore InconsistentNaming

		private bool _contentLoaded;

		public void InitializeComponent()
		{
			if (_contentLoaded)
			{
				return;
			}
			_contentLoaded = true;

			StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);

			//var resourceLocater = new Uri("/XTrace.Viewer;component/app.xaml", UriKind.Relative);
			//LoadComponent(this, resourceLocater);
		}

		[STAThread]
		public static void Main()
		{
			Thread.CurrentThread.Name = "Main Application Thread";
#if DEBUG
			// Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-ru");
#endif

			// ProfilingHelper.EnableProfiling();

			new StructuredTextFileXTraceListener("XTraceViewer", RelativePath.TempFolder);
			new BridgeFromTraceToXTrace();

			Trace.Information("Started with parametersCount", Environment.GetCommandLineArgs().Join(" "));

			Trace.Important("TEST");
			Trace.Information("TEST");
			Trace.Warning("TEST");
			Trace.Error("TEST");
			Trace.Verbose("TEST");

			ThreadPool.QueueUserWorkItem(TryRegisterFile);

			var app = new App();
			app.InitializeComponent();
			app.Run();

			Trace.Information("Stopped");
		}

		static void TryRegisterFile(object state)
		{
			TryRegisterExtension(Microsoft.Win32.Registry.ClassesRoot);
			TryRegisterExtension( Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, RegistryView.Default).OpenSubKey("", true));
		}

		/// <summary>
		/// Register extension
		/// </summary>
		/// <param name="registryKey"></param>
		[DebuggerStepThrough]
		private static void TryRegisterExtension(RegistryKey registryKey)
		{
			var path = Assembly.GetExecutingAssembly().Location;

			try
			{
				using (var key = registryKey.CreateSubKey(".xlog"))
				{
					if (key != null)
					{
						key.SetValue("Content Type", "text/plain");
						using (var key2 = key.CreateSubKey(@"Shell\Open\Command"))
						{
							if (key2 != null)
							{
								key2.SetValue(null, @"""{0}"" ""%1""".Arg(path));
							}
						}
						using (var key2 = key.CreateSubKey(@"DefaultIcon"))
						{
							if (key2 != null)
							{
								key2.SetValue(null, @"""{0}""".Arg(path));
							}
						}

					}
				}
			}
			catch (UnauthorizedAccessException ex)
			{
				Trace.Warning("Could not register file extension", ex.ToString());
			}
		}
	}
}